package com.ivo.sys.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import com.ivo.core.WebConstants;
import com.ivo.util.WebUtils;

public class LoginInterceptor extends HandlerInterceptorAdapter {
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		if (handler instanceof ResourceHttpRequestHandler)
			return true;
		Class<?> clazz;
		if (handler instanceof HandlerMethod) {
			clazz = ((HandlerMethod) handler).getBeanType();
		} else
			clazz = handler.getClass();
		if (clazz.getAnnotation(WithoutLoginCheck.class) != null)
			return true;
		if (WebUtils.getSessionAttribute(request, WebConstants.SessionUser) == null) {
			if (request.getHeader("x-requested-with") == null)
				response.sendRedirect(WebUtils.makeUrl("login.do?url="
						+ WebUtils.getCurrentUrl(request, true)));
			else
				response.getWriter().write("");
			return false;
		}
		return true;
		
	}
}
